// pages/site/site.js
let siteList = require("../../utils/site")
let { getSite, addSite, updateSite, deleteSite } = require("../../api/site")
var appInfo = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    suw: false,
    from: {
      site: [],
      uid: appInfo.globalData.openid
    }
  },
  addBtn() {
    this.setData({
      show: true,
    })
  },
  siteFn() {
    this.setData({
      suw: true
    })
  },
  assign(e) {
    let type = e.target.dataset.type
    this.data.from[type] = e.detail.value
  },
  fz(e) {
    let arr = []
    e.detail.values.forEach(v => {
      arr.push(v.name)
    });
    console.log(arr)
    this.data.from.site = arr
    this.setData({
      suw: false,
      from: this.data.from
    })
  },
  //确认
  onsubmit() {
    let from = { ...this.data.from }
    from.site = from.site.join(",")
    addSite({ ...from, uid: appInfo.globalData.openid })
    this.setData({
      suw: false,
      show: false,
      from: {}
    })
    this.getSites()
  },

  onChange(e) {
    updateSite({ oldId: this.data.isId, newId: e.target.dataset.id })
    this.setData({
      isId: e.target.dataset.id
    })
  },

  //删除
  delete(e) {
    let id = e.target.dataset.id
    let index = e.target.dataset.index
    this.data.sitedata.splice(index, 1)
    this.setData({
      sitedata: this.data.sitedata
    })
    deleteSite({ id })
  },

  onClickHide() {
    this.setData({ show: false });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      siteList: siteList.default,
      from: JSON.parse(options.item || '{}'),//赋值
      suw: false
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.getSites()
  },

  async getSites(params) {
    let r = await getSite({ uid: appInfo.globalData.openid })
    console.log(r)
    r.data.map(v => {
      if (v.priority) {
        this.setData({
          isId: v.id
        })
      }
    })
    this.setData({
      sitedata: r.data
    })
  },

  amend(e) {
    e.target.dataset.item.site = e.target.dataset.item.site.split(",")
    let item = e.target.dataset.item
    console.log(item)
    this.setData({
      show: true,
      from: item
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})